package net.homeftp.heimo.weddingwidget;

import java.util.Date;

import net.homeftp.heimo.weddingwidget.core.CorrectDate;
import net.homeftp.heimo.weddingwidget.core.DateHelper;
import net.homeftp.heimo.weddingwidget.perf.MyPreferenceManager;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.TypedValue;
import android.view.View;
import android.widget.RemoteViews;

public class WeddingWidgetHelper {
	private static final String TAG = "WeddingWidgetHelper";
	private Context ctx = null;
	private MyPreferenceManager sPref = null;

	public WeddingWidgetHelper(Context ctx, MyPreferenceManager sPref) {
		this.ctx = ctx;
		this.sPref = sPref;
	}

	public RemoteViews getUpdateView(RemoteViews rv) {
		fnSetCounter(rv);
		fnSetTopText(rv);
		fnSetBottomText(rv);
		return rv;
	}

	/* open the function for preview */
	public int fnGetAlphaBGColor(int color) {
		int alpha = sPref.getPrefBasicAlphaIn255Scale();

		int red = Color.red(color);
		int green = Color.green(color);
		int blue = Color.blue(color);
		int newColor = Color.argb(alpha, red, green, blue);
//		Log.v(TAG, sPref.getAppId() + " ->  BG : " + newColor);
		return newColor;
	}

	private void fnSetCounter(RemoteViews rv) {
		String days = fnGetDayInStringPattern();
		rv.setImageViewBitmap(R.id.counter_img, buildBitmapUpdate(days, false));

		int color = sPref.getPrefCounterBG();
		fnSetBGForView(rv, R.id.counter_img, color);
//		Log.v(TAG, sPref.getAppId() + " ->  Counter : " + days);
	}

	/* open the function for preview */
	public String fnGetDayInStringPattern() {
		String display = "";
		Date targetDate = sPref.getPrefAnniversary();
		int pattern = sPref.getPrefCounterPattern();
		CorrectDate cAge = null;
		switch (pattern) {
		case 1: // days
			int numberOfDay = DateHelper
					.getCorrectedDay(new Date(), targetDate);
			display = String.valueOf(numberOfDay) + " d";
			break;
		case 2:// months
			cAge = DateHelper.getCorrectedDate(new Date(), targetDate);
			display = String.format("%.1f", cAge.getGetAgeInMonthBase()) + " m";
			break;
		case 3:// years
			cAge = DateHelper.getCorrectedDate(new Date(), targetDate);
			display = String.format("%.1f", cAge.getGetAgeInYearBase()) + " y";
			break;
		case 4:// Ymd
			cAge = DateHelper.getCorrectedDate(new Date(), targetDate);
			display = cAge.toString();
			break;
		default:
			numberOfDay = DateHelper.getCorrectedDay(new Date(), targetDate);
			display = String.valueOf(numberOfDay);
			break;
		}
		return display;
	}

	/* open the function for preview */
	public Bitmap buildBitmapUpdate(String text, boolean isPreview) {
		Resources resources = ctx.getResources();
		float dp = resources.getDisplayMetrics().density;
		int density = resources.getDisplayMetrics().densityDpi;
		
		int themeCfg = sPref.getPrefTheme();
		int fontColor = sPref.getPrefCounterFontBG();

		int defaultFontColor = ctx.getResources().getColor(
				R.color.color_deep_grey);
		int defaultShadowColor = ctx.getResources().getColor(
				R.color.color_light_grey);

		// fontColor = (isPreview) ? defaultFontColor : fontColor;

//		Log.v(TAG, sPref.getAppId() + " ->  Theme:" + themeCfg + " FontBg:"+ fontColor);

		Typeface font = null;
		switch (themeCfg) {
		case 0:
			font = Typeface.MONOSPACE;
			break;
		case 1:
			font = Typeface.createFromAsset(ctx.getAssets(),
					"fonts/GreatVibes-Regular.otf");
			break;
		case 2:
			font = Typeface.DEFAULT_BOLD;
			break;
		case 3:
			font = Typeface.createFromAsset(ctx.getAssets(),
					"fonts/Miss_Ellen.ttf");
			break;
		case 4:
			font = Typeface.createFromAsset(ctx.getAssets(),
					"fonts/FFF_Tusj.ttf");
			break;
		case 5:
			font = Typeface.createFromAsset(ctx.getAssets(),
					"fonts/orbitron-bold.otf");
			break;
		case 6:
			font = Typeface.createFromAsset(ctx.getAssets(),
					"fonts/Carrington.ttf");
			break;
		default:
			font = Typeface.MONOSPACE;
			break;
		}
		// int bitmapWidth = (int) (240/dp);
		int bitmapWidth = (int) (80 * dp);
		int bitmapHeigth = (int) (60 * dp);
		Bitmap myBitmap = Bitmap.createBitmap((int)(160*dp), (int)(84*dp), Bitmap.Config.ARGB_4444);
		myBitmap.setDensity(density); // ScaleDown
		// Bitmap myBitmap = Bitmap.createBitmap(160, 84,
		// Bitmap.Config.ARGB_4444);
		Canvas myCanvas = new Canvas(myBitmap);
		Paint paint = new Paint();
		paint.setAntiAlias(true);
		paint.setSubpixelText(true);
		paint.setTypeface(font);
		paint.setStyle(Paint.Style.FILL);
		paint.setColor(fontColor);
		int counterFontSize = 40;
		if (text.length() >= 6) {
			counterFontSize = 25;
		}
		if (isPreview) {
			paint.setColor(defaultFontColor);
			paint.setShadowLayer(2f, 1f, 1f, defaultShadowColor);
			counterFontSize = counterFontSize-5;
		}
		paint.setTextSize(counterFontSize * dp);
		paint.setTextAlign(Align.CENTER);
		myCanvas.drawText(text, bitmapWidth, bitmapHeigth, paint);
		// myCanvas.drawText(text, (80*scale), (60*scale), paint);
		// Bitmap myBitmap = drawTextToBitmap(R.id.counter_img,text);

//		Log.v(TAG, sPref.getAppId() + " ->  Width:" + bitmapWidth + " Height:" + bitmapHeigth + " DP:" + dp+ " density:"+density);
		return myBitmap;
	}

	private void fnSetBottomText(RemoteViews rv) {
		String bottomText = sPref.getPrefBText();
		if (bottomText.length() > 0 && !bottomText.equalsIgnoreCase("")) {
			rv.setViewVisibility(R.id.bottom_text, View.VISIBLE);
			rv.setTextViewText(R.id.bottom_text, bottomText);

			int color = sPref.getPrefBtextBG();
			int fcolor = sPref.getPrefBtextFontBG();
			int size = sPref.getPrefBtextSize();
			fnSetBGForView(rv, R.id.bottom_text, color);
			fnSetFontColorForView(rv, R.id.bottom_text, fcolor);
			fnSetFontSizeForView(rv, R.id.bottom_text, size);
//			Log.v(TAG, sPref.getAppId() + " ->  BText : " + bottomText + ",bg:" + color + ",fbg:" + fcolor + ",fsize:" + size);
		} else {
			rv.setViewVisibility(R.id.bottom_text, View.GONE);
		}
	}

	private void fnSetTopText(RemoteViews rv) {
		String topText = sPref.getPrefTText();
		if (topText.length() > 0 && !topText.equalsIgnoreCase("")) {
			rv.setViewVisibility(R.id.top_text, View.VISIBLE);
			rv.setTextViewText(R.id.top_text, topText);

			int color = sPref.getPrefTtextBG();
			int fcolor = sPref.getPrefTtextFontBG();
			int size = sPref.getPrefTtextSize();

			fnSetBGForView(rv, R.id.top_text, color);
			fnSetFontColorForView(rv, R.id.top_text, fcolor);
			fnSetFontSizeForView(rv, R.id.top_text, size);
//			Log.v(TAG, sPref.getAppId() + " ->  TText : " + topText + ",bg:" + color + ",fbg:" + fcolor + ",fsize:" + size);
		} else {
			rv.setViewVisibility(R.id.top_text, View.GONE);
		}
	}

	private void fnSetBGForView(RemoteViews rv, int viewID, int color) {
		int acolor = fnGetAlphaBGColor(color);
		rv.setInt(viewID, "setBackgroundColor", acolor);
	}

	private void fnSetFontColorForView(RemoteViews rv, int viewID, int color) {
		rv.setInt(viewID, "setTextColor", color);
	}

	private void fnSetFontSizeForView(RemoteViews rv, int viewID, int size) {
		int pixel= (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                size, ctx.getResources().getDisplayMetrics());
		rv.setFloat(viewID, "setTextSize", pixel);
	}

	private Bitmap drawTextToBitmap(int gResId, String gText) {
		Resources resources = ctx.getResources();
		float scale = resources.getDisplayMetrics().density;
		Bitmap bitmap = BitmapFactory.decodeResource(resources, gResId);
		Config bitmapConfig = bitmap.getConfig();
		if (bitmapConfig == null) {
			bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
		}
		// resource bitmaps are imutable,
		// so we need to convert it to mutable one
		bitmap = bitmap.copy(bitmapConfig, true);
		Canvas canvas = new Canvas(bitmap);
		// new antialised Paint
		Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		// text color - #3D3D3D
		paint.setColor(Color.rgb(61, 61, 61));
		// text size in pixels
		paint.setTextSize((int) (14 * scale));
		// text shadow
		paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);
		// draw text to the Canvas center
		Rect bounds = new Rect();
		paint.getTextBounds(gText, 0, gText.length(), bounds);
		int x = (bitmap.getWidth() - bounds.width()) / 2;
		int y = (bitmap.getHeight() + bounds.height()) / 2;
		canvas.drawText(gText, x * scale, y * scale, paint);
		return bitmap;
	}
}
